using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using cmd;
using UnityEngine.UI;

public class FishSpanwe : Singleton<FishSpanwe>
{
    [Header("鱼生成配置")]
    [SerializeField] private LevelDataModelSO LevelDataModelSO;
    private Fish fishPrefab;           // 鱼的预制体  
    [SerializeField] private Transform fishParent;      // 鱼的父对象
    [SerializeField] private bool printFishDetails = true;
    [Header("动画时长")]
    [SerializeField] private float animationLength = 1f;
    [Header("鱼的游动空间设置")]
    [SerializeField] private Collider2D Fishapace;

    [Header("下潜的层数判断")]
    [SerializeField] private int LayerCount;
    [SerializeField] private int NowlayerCount;
    [SerializeField] private Button Dive_button;
    private List<PickableItemDataDTO> allPickableItems = new List<PickableItemDataDTO>();
    private List<Fish> spawnedFishes = new List<Fish>(); // 已生成的鱼列表


    //private Camera mainCamera;


    public void Awake()
    {
        PlayerPrefs.SetInt("level", 0);
        NowlayerCount = PlayerPrefs.GetInt("level");
        LayerCount = LevelDataModelSO.LayerCount;
    }

    // 收集数据并生成鱼
    public void CollectAndSpawnFish()
    {
        CollectAllPickableItems();
        SpawnAllFish(); // 直接生成所有鱼，不使用协程
    }

    public void CollectAllPickableItems()
    {
        allPickableItems.Clear();

        if (LevelDataModelSO == null)
        {
            Debug.LogError("未分配LevelLayerDataSO");
            return;
        }

        // 从关卡层数据获取所有物品DTO
        var (layesSO, items) = LevelDataModelSO.GetPickableItemsInLayer(PlayerPrefs.GetInt("level"));
        Debug.Log("当前的关卡为" + PlayerPrefs.GetInt("level"));
        LevelManager.Instance.CurrentLevel = PlayerPrefs.GetInt("level");
        // 添加到列表
        allPickableItems.AddRange(items);

        Debug.Log($"成功收集 {allPickableItems.Count} 个可拾取物品");

        // 打印鱼类详细信息
        //if (printFishDetails)
        //{
        //    PrintFishDetails();
        //}
    }

    // 直接生成所有鱼
    private void SpawnAllFish()
    {
        foreach (var item in allPickableItems)
        {
            // 检查是否为鱼类DTO
            if (item is FishDataDTO fishData)
            {
                SpawnFish(fishData);
            }
        }
    }

    private Fish SpawnFish(FishDataDTO fishData)
    {
        fishPrefab = Resources.Load<Fish>("Fishprefab/" + fishData.Name.ToString());
        Debug.Log("这里是输出的鱼" + fishData.Name.ToString());

        // 计算鱼的生成位置
        Vector3 spawnPosition = CalculateSpawnPosition(fishData.SpawnRangePercent, Fishapace);

        // 实例化鱼对象
        Fish fishInstance = Instantiate(fishPrefab, spawnPosition, Quaternion.identity);

        // 设置父对象
        if (fishParent != null)
        {
            fishInstance.transform.SetParent(fishParent);
        }

        // 初始化鱼的数据
        fishInstance.Initialize(fishData);

        // 保存到已生成列表
        spawnedFishes.Add(fishInstance);

        return fishInstance;
    }

    // 计算鱼的生成位置
    private Vector3 CalculateSpawnPosition(float spawnRangePercent, Collider2D spawnBounds)
    {
        if (spawnBounds == null)
        {
            Debug.LogError("Spawn bounds collider is not assigned!");
            return Vector3.zero;
        }

        // 获取边界区域
        Bounds bounds = spawnBounds.bounds;

        // 水平方向上的随机偏移（使用边界宽度的80%）
        float horizontalOffset = Random.Range(-bounds.size.x * 0.4f, bounds.size.x * 0.4f);

        // 竖直方向上的偏向设置（基于百分比调整）
        float verticalOffset = bounds.size.y * (spawnRangePercent / 100 - 0.5f);

        // 以边界中心为基准计算生成位置
        return new Vector3(
            bounds.center.x + horizontalOffset,
            bounds.center.y + verticalOffset,
            bounds.center.z);
    }


    public void Dive()
    {
        GameObject[] fishObjects = GameObject.FindGameObjectsWithTag("Fish");
        foreach (GameObject fish in fishObjects)
        {
            Destroy(fish);
        }
        Debug.Log($"成功删除 {fishObjects.Length} 个Fish物体");
        StartCoroutine(DiveProcess());

    }

    IEnumerator DiveProcess()
    {
        //给下潜动画留的位置
        yield return new WaitForSeconds(animationLength);

        NowlayerCount++;
        PlayerPrefs.SetInt("level", NowlayerCount);

        if (NowlayerCount >= LayerCount - 1)
        {
            Dive_button.interactable = false;
        }
        CollectAndSpawnFish();
    }



    //// 新增方法：打印所有鱼类DTO的详细信息
    //private void PrintFishDetails()
    //{
    //    int fishCount = 0;

    //    foreach (var item in allPickableItems)
    //    {
    //        // 检查是否为鱼类DTO
    //        if (item is FishDataDTO fishData)
    //        {
    //            fishCount++;

    //            // 构建详细信息字符串
    //            string fishInfo = $"鱼 #{fishCount}:\n" +
    //                $"  名称: {fishData.Name}\n" +
    //                $"  品质: {fishData.Quality}\n" +
    //                $"  体积: {fishData.Volume:F2}\n" +
    //                $"  移动速度: {fishData.MoveSpeed:F2}\n" +
    //                $"  生成高度百分比: {fishData.SpawnRangePercent:F2}%\n" +
    //                $"  种类: {fishData.FishType.Name}\n" +
    //                $"  基础重量: {fishData.BaseWeight:F2} kg\n" +
    //                $"  单位价值: {fishData.UnitValue:F2}";

    //            Debug.Log(fishInfo);
    //        }
    //    }

    //    if (fishCount == 0)
    //    {
    //        Debug.Log("未找到鱼类物品");
    //    }
    //    else
    //    {
    //        Debug.Log($"共找到 {fishCount} 条鱼");
    //    }
    //}



}
